import {defineStore} from "pinia";
import {getToken, removeToken} from '~/utils/storage/cookie.js';
import {getWhoami, getDomains} from "~/utils/axios/login.js";
import {useRouter, useRoute} from "vue-router";
import {reactive, ref} from 'vue';
import {ElMessage} from 'element-plus'
import WebSocketService from './websocket.service';
import { req_getProductionInfo } from "~/utils/axios/index.js";

export const useUserStore = defineStore('user', () => {
    let $route = useRoute();
    let $router = useRouter();
    const token = getToken()
    const loginState = ref(false)
    const name = ref();
    const domains = ref('')
    const roleLevel = ref('')
    // 产品名称
    const productName = ref()
    // 
    const socket = ref();

    const commonEvent = (message) => {
        ElMessage({
            message: `设备 ${message.ip} ${message.message}`,
            type: 'success',
        })
    }

    const initUser = async () => {
        const whoami = await getWhoami()
        const tathDomains = await getDomains()
        const productionInfo = await req_getProductionInfo();
        // socket.value = new WebSocketService('ws://172.16.50.103:8080/soc');
        stopConnection();
        try {//这里可能失败，会导致后面的代码不执行
            if (window.location.protocol === 'https:') {
                socket.value = new WebSocketService(`wss://${window.location.hostname}:8080/soc`);
            } else if (window.location.protocol === 'http:') {
                socket.value = new WebSocketService(`ws://${window.location.hostname}:8080/soc`);
            }
        } catch {
            console.log('WebSocketService 失败')
        }
        
        socket.value.addListener("common", commonEvent);

        // socket.value.onmessage = (event) => {
        //     let thisData = JSON.parse(event.data) // 更新数据
        //     ElMessage({
        //         message: `设备 ${thisData.ip} ${thisData.message}`,
        //         type: 'success',
        //     })
        // };
        name.value = whoami.data.user.name;
        roleLevel.value = whoami.data.user._roles[0].roleLevel;
        domains.value = tathDomains.data[0]
        // 这里是解决同浏览器不同会话下右侧页面不刷新的问题
        if (sessionStorage.getItem("username") === null) {
            sessionStorage.setItem("username", whoami.data.user.name);
        }
        if (sessionStorage.getItem("productInfo") === 'undefined' || !sessionStorage.getItem("productInfo")) {
            sessionStorage.setItem("productInfo", JSON.stringify(productionInfo));
        }
        sessionStorage.setItem("register", JSON.stringify(whoami.data.user));
        // if (!whoami.data.user.isRegister) {
        //     $router.push({
        //         path: "/password",
        //         query: {
        //             name: whoami.data.user.name,
        //             userId: whoami.data.user.userId,
        //         },
        //     });
        // }
        if (sessionStorage.getItem("username") != whoami.data.user.name) {
            if (whoami.data.user.name === 'root') {
                $router.push("/DOMAIN");
            } else if (whoami.data.user._roles[0].name === '安全审计员') {
                $router.push("/auditlog");
            } else if (whoami.data.user._roles[0].name === '系统管理员') {
                $router.push("/systemsetting");
            } else if ($route.path != "/home") {
                $router.push("/home");
            }
            sessionStorage.setItem("username", whoami.data.user.name);
        }
    }

    const removeUser = () => {
        name.value = ''
    }
    const stopConnection = () => {
        if (socket.value) {
            // socket.value.removeListener("common", commonEvent);
            // socket.value = null;  // 清空 socket 变量
            socket.value.close();  // 清空 socket 变量
        }
    };
    return {
        name,
        loginState,
        domains,
        roleLevel,
        socket,
        removeUser,
        stopConnection,
        initUser,
        productName
    }
})